<template>
  <div class="main-container">
    <div class="main-container__main">
      <div class="main-container-main__title main-container-main__title--spacing-small">
        忘记密码？
      </div>
      <el-steps class="main-container-main__steps" :active="currentStep" align-center finish-status="success">
        <el-step title="填写账户"></el-step>
        <el-step title="接受验证码"></el-step>
        <el-step title="设置密码"></el-step>
      </el-steps>
      <template v-if="currentStep === 0">
        <!-- step 1 -->
        <el-form class="main-container-main__form" :model="form" :rules="rules" ref="form" :disabled="loading"
                 @submit.native.prevent="firstStep"
        >
          <el-form-item class="main-container-main__item" prop="username" :error="formError">
            <el-input class="main-container-main__input" v-model="form.username"  placeholder="请输入账户名或手机号码" auto-complete="off">
              <template slot="prepend">
                <svg-icon icon-class="user"></svg-icon>
              </template>
            </el-input>
          </el-form-item>

          <!--<el-form-item class="main-container-main__item" prop="code" :error="formError">-->
            <!--<el-input v-model="form.code" placeholder="请输入验证码" auto-complete="off">-->
              <!--<template slot="prepend">-->
                <!--<svg-icon icon-class="login-security"></svg-icon>-->
              <!--</template>-->
              <!--<template slot="append">-->
                <!--<validate-img  class="main-container-main__img-code"  ref="validateImg" />-->
              <!--</template>-->
            <!--</el-input>-->
          <!--</el-form-item>-->
          <Captcha :callback="getResult" :showCaptcha="showCaptcha" :captchaClose="captchaClose"></Captcha>
          <el-row type="flex" justify="center" align="middle">
            <el-button type="primary" native-type="submit" block>确 定</el-button>
          </el-row>
        </el-form>

      </template>

      <!-- step 2 -->
      <template v-else-if="currentStep === 1">
        <el-form ref="selectForm" :model="selectForm" @submit.native.prevent="confirmFindWay('selectForm')">
          <el-form-item prop="type" :error="formError">
            <el-radio-group v-model="selectForm.type">
              <el-radio label="mobile" class="main-container-main__radio" v-if="!!userData.telephone">
                <div class="main-container-main__radio-label">
                  将验证码发送到手机号码
                  <div class="main-container-main__radio-tip">手机：{{userData.telephone}}</div>
                </div>
              </el-radio>
              <el-radio label="email" class="main-container-main__radio" v-if="!!userData.email">
                <div class="main-container-main__radio-label">
                  将验证码发送至注册《电子邮箱》
                  <div class="main-container-main__radio-tip">邮箱：{{userData.email}}</div>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <section class="main-container-main__btn-group">
            <el-button @click="prevStep">返回</el-button>
            <el-button type="primary" native-type="submit">下一步</el-button>
          </section>
        </el-form>
      </template>
      <!-- step 3 -->
      <template v-else-if="currentStep === 2">
        <el-form :model="submitForm" :rules="submitFormRules" ref="submitForm"
                 @submit.native.prevent="doSave({action: 'submit', form: 'submitForm'})"
        >
          <p>
            <template v-if="selectForm.type === 'mobile'">
              验证码已经发送到手机: {{userData.telephone}}
            </template>
            <template v-else-if="selectForm.type === 'email'">
              验证码已经发送到手机: {{userData.email}}
            </template>
          </p>
          <el-form-item class="main-container-main__item" prop="code" :error="formError">
            <el-input class="main-container-main__input" v-model="submitForm.code" placeholder="请输入验证码" auto-complete="off">
              <template slot="prepend">
                <svg-icon icon-class="login-security"></svg-icon>
              </template>
              <template slot="append">
                <el-button size="medium" @click="sendCode({formItem: 'mobile'})" type="dark" :disabled="sendingCode">
                  {{codeBtnText}}
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="main-container-main__item" prop="password">
            <password-input v-model="submitForm.password" placeholder="8-20个数字/字母/特殊字符组成" auto-complete="off"></password-input>
          </el-form-item>
          <el-form-item class="main-container-main__item" prop="newPwd">
            <password-input v-model="submitForm.newPwd" placeholder="8-20个数字/字母/特殊字符组成" auto-complete="off"></password-input>
          </el-form-item>

          <section class="main-container-main__btn-group">
            <el-button @click="prevStep">返回</el-button>
            <el-button type="primary" native-type="submit">完成</el-button>
          </section>
        </el-form>
      </template>

      <el-row class="main-container__links" type="flex" justify="space-between" v-if="currentStep === 0">
        <router-link :to="{name: 'register'}" class="main-container__link hidden">
          <svg-icon icon-class="arrow-right" type="primary" :stroke="true" :reverse="true"></svg-icon>
          去注册
        </router-link>
        <router-link :to="{name: 'login'}" class="main-container__link">
          去登录
          <svg-icon icon-class="arrow-right" type="primary" :stroke="true"></svg-icon>
        </router-link>
      </el-row>
    </div>

    <div class="main-container__footer">
      <customer-service class="main-container__footer-custom">
        <svg-icon icon-class="login-customer-service" type="primary"></svg-icon>7*24小时在线客服
      </customer-service>
    </div>
  </div>
</template>

<script type="text/jsx">
  import {factory, form, getCode} from '@/build';

  import {
    getUserForgetInfoApi as infoApi,
    getUserForgetCodeApi as codeApi,
    userForgetResetPasswordApi as saveApi,
  } from '@/services/api/user';
  import Captcha from '@/components/captcha';

  export default {
    name: "forget-password",

    mixins: [form, getCode],
  
    components:{
      Captcha
    },

    data() {
      return {
        codeApi,
        sendingData: 'selectForm',

        currentStep: 0,
  
        captchaStatus: false, //验证是否成功，
        showCaptcha: false, // 是否显示验证,

        //step-1
        form: {
          username: '',
          code: '',
          mobile: '1',
        },
        rules: {
          username: factory.getRule('usernameOrMobile'),
          code: [
            {required: true, message: '请输入验证码', trigger: 'blur'}
          ]
        },

        formError: '',

        userData: {},

        //step-2
        selectForm: {
          type: '',
          imgCode: '',
          username: '',
        },

        //step-3
        submitForm: {
          username: 'username',
          code: '',
          password: '',
          newPwd: '',
          imgCode: '',
          type: '',
        },
        submitFormRules: {
          password: factory.getRule('password'),
          newPwd: [
            {required: true, message: '请再次输入密码'},
            {
              validator: (rule, value, callback) => {
                if (value === '') {
                  callback();
                } else if (value !== this.submitForm.password) {
                  callback(new Error('两次输入密码不一致!'));
                } else {
                  callback();
                }
              }
            }
          ],
        },
      };
    },
    methods: {
      confirmFindWay(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.selectForm.imgCode = this.form.code;
            this.selectForm.username = this.form.username;

            this.sendCode({formItem: 'mobile'});

            this.currentStep++;
          } else {
            return false;
          }
        });
      },

      prevStep() {
        this.formError = '';
        this.currentStep--;
      },

      finish() {
        this.$message({
          message: '新密码设定成功',
        });
      },
      captchaClose() {
        this.captchaStatus = false;
        this.showCaptcha = false;
      },
      getResult(err, data) {
        this.captchaStatus = data ? !!data.validate : false;
        this.form.validate = data ? data.validate : "";
        this.captchaStatus ? this.doSave({action: 'confirmUsername', form: 'form'}) : null;
      },
      firstStep(){
        if(!this.form.username){
          this.doSave({action: 'confirmUsername', form: 'form'});
        }
        if(this.form.username){
          this.showCaptcha = true;
        }
      }
    },

    mounted() {
      this.bindSave(infoApi, 'confirmUsername', 'form', {
        beforeSend: (data) => {
          this.formError = '';

          return data;
        },
        callback: ([result, data]) => {
          if (!result) {
            this.formError = data.message;
            this.$refs.validateImg.change();
          } else {

            this.userData = data;
            if (data.telephone) {
              data.telephone = data.telephone.indexOf('+') > -1 ? data.telephone : `+${data.telephone}`;
              this.selectForm.type = 'mobile';
            } else if (data.email) {
              this.selectForm.type = 'email';
            }

            //有无找回方式
            if (this.selectForm.type) {
              this.currentStep++;
              this.captchaClose();
            } else {
              const vm = this.$messageTip({
                message: <div>您还没有绑定手机和电子邮箱。<br />请联系客服。</div>,
                width: consts.DIALOG_SIZE_NORMAL,
                goTo: <customer-service nativeOnClick={() => {vm.close();}}><el-button type="primary" block>联系客服</el-button></customer-service>
              });
            }
          }
        }
      });

      this.bindSave(saveApi, 'submit', 'submitForm', {
        beforeSend: (data) => {
          this.formError = '';
          this.submitForm.username = this.form.username;
          this.submitForm.imgCode = this.form.code;
          this.submitForm.type = this.selectForm.type;

          return data;
        },
        callback: ([result, data]) => {
          if (!result) {
            this.formError = data.message;
          } else {

            const vm = this.$messageTip({
              message: '新密码修改成功，请重新登录账号',
              showClose: false,
              type: 'success',
              goTo: <router-link nativeOnClick={() => {vm.close();}} to={
                {
                  name: 'login'
                }
              }><el-button type="primary" block="true">确定</el-button></router-link>
            });
          }
        }
      });
    },
    beforeDestroy() {
      this.showCaptcha = false;
    },
  };
</script>
